package api

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"gligli/middleware"
	"gligli/model"
	"gligli/serializer"
	"gligli/service"
	"os"
	"strconv"
	"time"
)

// UserRegister 用户注册接口
func UserRegister(c *gin.Context) {
	var service service.UserRegisterService
	if err := c.ShouldBind(&service); err == nil {
		res := service.Register()
		c.JSON(200, res)
	} else {
		c.JSON(200, ErrorResponse(err))
	}
}

// MsgCode 发送短信验证码接口
func MsgCode(c *gin.Context) {
	var service service.MsgCodeService
	if err := c.ShouldBind(&service); err == nil {
		fmt.Println(service)
		res := service.Send(service)
		c.JSON(200, res)
	} else {
		c.JSON(200, ErrorResponse(err))
	}
}

//generate jwt token
func genToken(claims *model.JWTClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedToken, err := token.SignedString([]byte(os.Getenv("JWT_Secret")))
	if err != nil {
		return "", errors.New(model.ErrorServerBusy)
	}
	return signedToken, nil
}

// UserLogin 用户登录接口
func UserLogin(c *gin.Context) {
	var service service.UserLoginService
	if err := c.ShouldBind(&service); err == nil {
		if user, err := service.Login(); err != nil {
			c.JSON(200, err)
		} else {
			//c.SetCookie("user_id", strconv.FormatUint(uint64(user.ID), 10), 3600, "/", os.Getenv("Cookie_Domain"), false, false)
			// 设置Session
			//s := sessions.Default(c)
			//s.Clear()
			//s.Set("user_id", user.ID)
			//s.Save()
			// 改用JWT模式
			claims := &model.JWTClaims{
				ID: user.ID,
			}
			ExpireTime, _ := strconv.ParseInt(os.Getenv("Token_Expire_Time"), 10, 64) //token expire time
			claims.IssuedAt = time.Now().Unix()
			claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(ExpireTime)).Unix()
			singedToken, err := genToken(claims)
			if err != nil {
				c.String(200, err.Error())
				return
			}
			c.SetCookie("token", singedToken, 3600 * 2, "/", os.Getenv("Cookie_Domain"), false, false)

			//res := serializer.BuildUserResponse(user)
			c.JSON(200, serializer.Response{
				Status: 0,
				Msg:    "登录成功",
				Data:   singedToken,
			})
		}
	} else {
		c.JSON(200, ErrorResponse(err))
	}
}

// UserMe 用户详情
func UserMe(c *gin.Context) {
	user := CurrentUser(c)
	res := serializer.BuildUserResponse(*user)
	c.JSON(200, res)
}

// UserLogout 用户登出
func UserLogout(c *gin.Context) {
	/*
		begin：session登出方式
	*/
	//s := sessions.Default(c)
	//s.Clear()
	//s.Save()
	/*
		end：session登出方式
	*/
	// 改为JWT方式登出
	/*
	begin：JWT方式登出
	*/
	strToken := c.Request.Header.Get("token")
	claims, err := middleware.VerifyAction(strToken)
	if err != nil {
		c.JSON(200, err)
		return
	}
	// 将token的过期时间设置成现在，这样使token过期
	claims.ExpiresAt = time.Now().Unix() - 1000
	signedToken, err := genToken(claims)
	if err != nil {
		c.JSON(200, err)
		return
	}
	c.SetCookie("token", signedToken, 3600 * 2, "/", os.Getenv("Cookie_Domain"), false, false)
	/*
	end：JWT方式登出
	 */

	c.JSON(200, serializer.Response{
		Status: 0,
		Msg:    "登出成功",
		Data:   signedToken,
	})
}
